<template>
  <div>
    <div class="gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="6" :lg="4">
          <p>选手姓名</p>
          <el-input v-model="finalCompetitionRegisterQO.Filter" placeholder="请输入" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="6" :lg="4">
          <p>可报赛区</p>
          <el-input v-model="finalCompetitionRegisterQO.SubCompetitionName" placeholder="请输入" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="6" :lg="4">
          <p>所属机构</p>
          <el-input v-model="finalCompetitionRegisterQO.DelegationName" placeholder="请输入" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="8" :lg="6" align="left" class="search_btn">
          <!-- 查询按钮 -->
          <el-button type="primary" size="mini" @click="getPageList()">{{ $t('button.query') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="12">
        <el-button type="primary" size="mini" @click="handleAddPerson">增加人员</el-button>
        <el-button type="primary" size="mini" @click="handleClear">清空名单</el-button>
        <el-button type="primary" size="mini" @click="handleUpdeta">更新名单</el-button>
      </el-col>
      <el-col :span="12" style="text-align:right">
        <el-button :loading="btnLoading" size="mini" @click="downModelFile()">下载模板</el-button>
        <el-upload
          class="upload_file"
          :action="importAction"
          :before-upload="beforeUpload"
          :http-request="upLoadFile"
          :auto-upload="true"
          :show-file-list="false"
          accept=".xlsx, .xls"
        >
          <el-button :loading="btnUpLoading" size="mini">导入名单</el-button>
        </el-upload>
        <el-button :loading="btnLoading" size="mini" @click="downFile()">导出名单</el-button>
      </el-col>
    </el-row>
    <!-- 赛事列表 -->
    <el-table v-loading="tableLoading" class="gl_mb_15 gl_mt_20 game_table_list" :data="tableData" stripe size="mini" style="width: 100%">
      <el-table-column type="index" align="center" label="序号" :width="100" />
      <el-table-column label="姓名" :width="240">
        <template slot-scope="{ row }">
          <img class="game_coverimg" :src="getStaticFileUrl(row.imagePath)" alt="" @error="errorPhoto">
          <span style="display: inline-block;margin-left: 15px;">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="idCardNumber" align="center" label="证件号" :width="170" />
      <el-table-column label="可报赛区" align="center" :min-width="300">
        <template slot-scope="{ row }">
          <span v-for="(item, index) in row.subCompetitionNames" :key="index">
            {{ item + (index == row.subCompetitionNames.length -1 ? '' : ' / ') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" :min-width="300">
        <template slot-scope="{ row }">
          <span v-for="(item, index) in row.delegationNames" :key="index">
            {{ item + (index == row.delegationNames.length -1 ? '' : ', ') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" width="200">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" style="color:#FF3434" @click="clickDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="text-align: center;" class="gl_pb_15">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="finalCompetitionRegisterQO.MaxResultCount"
        :current-page="finalCompetitionRegisterQO.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
    <!-- 增加人员弹框 -->
    <el-dialog title="增加人员" class="gl_dialog_TitleLine dialogVisible_addPerson" :visible.sync="dialogVisible_addPerson" :close-on-click-modal="false" width="880px">
      <el-scrollbar v-loading="dialogLoading" wrap-class="scrollbar-wrapper gl_dialog_height fixHeight">
        <el-row class="gl_mb_15">
          <el-col :span="24">
            <el-form ref="registerByPersonQO" label-position="right" :rules="categoryVO_Rules" style="width:95%" label-width="100px" :model="registerByPersonQO">
              <el-row class="gl_mb_15">
                <el-col :span="10">
                  <el-form-item label="会员姓名">
                    <el-input v-model="registerByPersonQO.Name" placeholder="请输入注册会员姓名" size="mini" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="证件号码">
                    <el-input v-model="registerByPersonQO.IdCardNumber" placeholder="请输入注册会员证件号码" size="mini" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="3" style="text-align: right">
                  <el-button type="primary" :loading="confirmLoading" size="mini" style="margin-top:6px" @click="handleConfirm">确认</el-button>
                </el-col>
              </el-row>
            </el-form>
            <!-- 分割线 -->
            <el-divider content-position="left">人员信息</el-divider>
          </el-col>
        </el-row>
        <el-row v-if="registerDto && registerDto.name" style="width:95%;margin:auto;padding-top:10px">
          <el-col :span="6">
            <div class="uploadBox gl_fr">
              <img class="uploadBox_people" :src="getStaticFileUrl(registerDto.imagePath)" alt="" @error="errorPhoto">
            </div>
          </el-col>
          <el-col :span="18">
            <el-form label-position="right" label-width="100px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="姓名:">
                    <span>{{ registerDto.name }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="证件号码:">
                    <span>{{ registerDto.idCardNumber }}</span>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="24">
                  <el-form-item label="所属机构:" />
                </el-col> -->
              </el-row>
            </el-form>
          </el-col>
          <el-col :span="24" class="gl_mt_20">
            <el-form label-position="right" label-width="100px">
              <el-form-item label="可选赛区:">
                <el-checkbox-group v-if="checkboxList.length > 0" v-model="checkboxData" size="mini" style="margin-top:5px">
                  <el-checkbox v-for="(item, index) in checkboxList" :key="index" :label="item.id" border>{{ item.name }}</el-checkbox>
                </el-checkbox-group>
                <span v-else>暂无可添加的赛区</span>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <row v-else>
          <el-col :span="24" style="text-align:center">
            暂无人员数据
          </el-col>
        </row>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button size="mini" @click="dialogVisible_addPerson = false">{{ $t('button.cancel') }}</el-button>
        <!-- 保存按钮 -->
        <el-button type="primary" :loading="submitLoading" :disabled="checkboxData.length === 0" size="mini" @click="handleSave">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import defaultGameLogo from '@/assets/images/game/game_logoDefaultPhoto.png';
import { CategoryVO_Rules } from '@/lib/validate/league';
import { translateByCode } from '@/lib/getTransData';
import {
  Api_GET_EventsManagementFinalCompetitionRegisterByPersonQO, Api_GET_EventsManagementFinalCompetitionRegisterQO, SiSTKWEventsManagementFinalCompetitionRegisterDto, SiSTKWEventsManagementUpdateFinalCompetitionRegisterInput
} from '@/lib/form/game/swaggerForm';
import { Api_GET_CompetitionQO } from '@/lib/form/events';
import {
  api_GET_EventsManagementFinalCompetitionRegister, api_GET_EventsManagementFinalCompetitionRegisterByPerson, api_GET_EventsManagementCompetitionChildren, api_PUT_EventsManagementFinalCompetitionRegister,
  api_POST_EventsManagementFinalCompetitionRegisterGenerateCompetitionId,
  api_DELETE_EventsManagementFinalCompetitionRegister,
  api_DELETE_EventsManagementFinalCompetitionRegisterByRegisterId
} from '@/extend/api/gameswaggerApi/app.js';
import { api_GET_DownLoadFileAddHeader, api_Post_UploadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';

export default {
  data() {
    return {
      importAction: `${process.env.VUE_APP_API_SWAGGER_GAME}/api/app/events-management/finalCompetitionRegister/import`,
      checkboxData: [],
      checkboxList: [],
      competitionQO: new Api_GET_CompetitionQO(),
      categoryVO_Rules: new CategoryVO_Rules(),
      defaultGameLogo: defaultGameLogo,
      registerByPersonQO: new Api_GET_EventsManagementFinalCompetitionRegisterByPersonQO(),
      registerDto: new SiSTKWEventsManagementFinalCompetitionRegisterDto(),
      finalCompetitionRegisterQO: new Api_GET_EventsManagementFinalCompetitionRegisterQO(),
      registerInput: new SiSTKWEventsManagementUpdateFinalCompetitionRegisterInput(),
      tableData: [],
      total: 0,
      dialogVisible_addPerson: false,
      submitLoading: false,
      btnUpLoading: false,
      btnLoading: false,
      confirmLoading: false,
      clearLoading: false,
      updataLoading: false,
      dialogLoading: false,
      tableLoading: false,
      file: '',
      gameId: ''
    };
  },
  created() {
    this.initForm();
    this.getCompetitionChildren();
  },
  methods: {
    // 获取分站赛列表
    getCompetitionChildren() {
      const _this = this;
      this.checkboxList = [];
      // 获取分站赛列表
      this.competitionQO.HasParent = true;
      this.competitionQO.HasFinalQualification = true;
      this.competitionQO.IsFinal = false;
      this.competitionQO.ParentId = this.gameId;
      this.competitionQO.TypeCode = 'League';
      this.competitionQO.MaxResultCount = 999;
      api_GET_EventsManagementCompetitionChildren(this.competitionQO).then(res => {
        this.checkboxList = res.items || [];
        console.log('🚀 ~ file: index.vue ~ line 231 ~ api_GET_EventsManagementCompetitionChildren ~ this.checkboxList', this.checkboxList);
      }, error => {
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 初始化
    initForm() {
      this.gameId = this.$route.params.parentId;
      this.finalCompetitionRegisterQO = new Api_GET_EventsManagementFinalCompetitionRegisterQO();
      this.getPageList();
    },
    // 获取赛事列表
    getPageList(page) {
      // 默认联赛
      this.finalCompetitionRegisterQO.CompetitionId = this.gameId;
      this.finalCompetitionRegisterQO.Page = page || 1;
      this.finalCompetitionRegisterQO.SkipCount = (this.finalCompetitionRegisterQO.Page - 1) * this.finalCompetitionRegisterQO.MaxResultCount;
      this.tableLoading = true;
      api_GET_EventsManagementFinalCompetitionRegister(this.finalCompetitionRegisterQO).then(res => {
        this.tableLoading = false;
        this.tableData = res.items || [];
        this.total = res.totalCount;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 增加人员
    handleAddPerson () {
      this.registerInput = new SiSTKWEventsManagementUpdateFinalCompetitionRegisterInput();
      this.registerByPersonQO = new Api_GET_EventsManagementFinalCompetitionRegisterByPersonQO();
      this.dialogVisible_addPerson = true;
    },
    // 清空名单
    handleClear() {
      const _this = this;
      const _confirmStr = '您确定要清空名单吗？';
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        this.clearLoading = true;
        api_DELETE_EventsManagementFinalCompetitionRegister({ competitionId: this.gameId }).then(res => {
          _this.clearLoading = false;
          _this.$message({ type: 'success', message: '清空成功！' });
          _this.getPageList(this.finalCompetitionRegisterQO.Page);
        }, error => {
          _this.clearLoading = false;
          const _msg = error.error.message || error.message;
          _this.$message({ type: 'error', message: _msg });
        });
      });
    },
    // 更新名单
    handleUpdeta() {
      const _this = this;
      const _confirmStr = '您确定要更新名单吗？';
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        this.updataLoading = true;
        api_POST_EventsManagementFinalCompetitionRegisterGenerateCompetitionId(this.gameId).then(res => {
          _this.updataLoading = false;
          _this.$message({ type: 'success', message: '更新成功！' });
          _this.getPageList(this.finalCompetitionRegisterQO.Page);
        }, error => {
          _this.updataLoading = false;
          const _msg = error.error.message || error.message;
          _this.$message({ type: 'error', message: _msg });
        });
      });
    },
    // 删除按钮
    clickDelete(row) {
      const _this = this;
      // 您确定要删除 xxx 吗？ zh
      const _confirmStr = ` ${translateByCode('alert.wantDelete')} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementFinalCompetitionRegisterByRegisterId({ competitionId: this.gameId, registerId: row.registerId }).then(res => {
          this.$message({
            type: 'success',
            // 删除成功！
            message: translateByCode('alert.deleteSuccessfully')
          });
          _this.getPageList(this.finalCompetitionRegisterQO.Page);
        }).catch(
          error => {
            const _msg = error.error.message || error.message;
            this.$message({
              duration: 15000,
              showClose: true,
              message: _msg,
              type: 'error'
            });
          }
        );
      });
    },
    // 弹框里的确认查询人员
    handleConfirm () {
      const _this = this;
      this.$refs.registerByPersonQO.validate(valid => {
        if (!valid) return;
        this.confirmLoading = true;
        this.registerDto = new SiSTKWEventsManagementFinalCompetitionRegisterDto();
        this.registerByPersonQO.CompetitionId = this.gameId;
        api_GET_EventsManagementFinalCompetitionRegisterByPerson(this.registerByPersonQO).then(res => {
          _this.confirmLoading = false;
          _this.registerDto = res || {};
          _this.checkboxData = _this.registerDto.subCompetitionIds || [];
        }, error => {
          _this.confirmLoading = false;
          const _msg = error.error.message || error.message;
          _this.$message({ type: 'error', message: _msg });
        });
      });
    },
    // 保存按钮
    handleSave () {
      const _this = this;
      // this.$refs.registerByPersonQO.validate(valid => {
      //   if (!valid) return;
      this.submitLoading = true;
      this.registerInput.competitionId = this.gameId;
      this.registerInput.registerId = this.registerDto.registerId;
      this.registerInput.subCompetitionsId = this.checkboxData;
      api_PUT_EventsManagementFinalCompetitionRegister(this.registerInput).then(res => {
        _this.$message({ type: 'success', message: '修改成功！' });
        _this.submitLoading = false;
        _this.dialogVisible_addPerson = false;
        _this.getPageList(this.finalCompetitionRegisterQO.Page);
      }, error => {
        _this.submitLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
      // });
    },
    beforeUpload(file) {
      this.file = file;
    },
    // 导入名单
    upLoadFile() {
      var _this = this;
      _this.btnUpLoading = true;
      api_Post_UploadFileAddHeader(this.importAction, this.file, { competitionId: this.gameId }).then(res => {
        _this.$message({
          type: 'success',
          duration: 10000,
          showClose: true,
          message: `导入成功,导入成功${res.successfulCount}条，失败${res.failedCount}条`
        });
        _this.getPageList(this.finalCompetitionRegisterQO.Page);
        _this.btnUpLoading = false;
      }).catch(error => {
        _this.btnUpLoading = false;
        _this.$message({
          type: 'error',
          message: '导入失败 ' + error || error.error.message
        });
      });
    },
    // 导出名单
    downFile() {
      var _this = this;
      this.btnLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '决赛名单' + '.xlsx';
      const params = {};
      params.ReportName = 'FinalCompetitionRegister';
      params.CompetitionId = this.gameId;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params).then(res => {
        _this.btnLoading = false;
      }).catch(error => {
        _this.btnLoading = false;
        errorText(error).then(function(text) {
          _this.$message({ type: 'error', message: text });
        });
      });
    },
    // 导出模板
    downModelFile() {
      var _this = this;
      this.btnLoading = true;
      const tempUrl = `static/ImportFinalLeagueNamesTemplate.xlsx`;
      const fileName = '名单模板' + '.xlsx';
      const downloadElement = document.createElement('a');
      const href = tempUrl;
      console.log(href);
      downloadElement.style.display = 'none';
      downloadElement.href = href;
      downloadElement.target = '_blank';
      downloadElement.download = fileName;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      _this.btnLoading = false;
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultGameLogo;
    },
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.finalCompetitionRegisterQO.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>
<style lang="scss" scoped>
  .statistics_title{
    line-height: 50px;
  }
  .statistics_label{
    text-align: right;
    font-weight: bold;
  }
  .statistics_nums{
    font-size: 40px;
    color: rgb(58, 128, 236);
    margin-bottom: 10px;
  }
  .game_table_list .game_coverimg {
    width: 74px;
    height: 74px;
    border-radius: 50%;
    vertical-align: middle;
  }
  .fixHeight {
    height: 500px;
  }
  .uploadBox{
    width: 180px;
    height: 180px;
  }
  .uploadBox_people{
    height: 100%;
    width: 100%;
  }
  .dialogVisible_addPerson .el-form-item{
    margin-bottom: 0;
  }
  .upload_file{
    display: inline-block;
    margin-right: 10px;
    margin-left: 10px;
  }
</style>
